package org.dromara.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.constant.MachineConstant;
import org.dromara.system.domain.SimUserLevelRecords;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.ManualModificationUserLevelBo;
import org.dromara.system.domain.bo.SimUserLevelRecordsBo;
import org.dromara.system.domain.bo.UserLevelBo;
import org.dromara.system.domain.vo.SimUserLevelRecordsVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.enums.QueryTypeEnum;
import org.dromara.system.mapper.SimUserLevelRecordsMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.ISimUserLevelRecordsService;
import org.dromara.system.service.ISysUserService;
import org.dromara.system.service.impl.permission.PermissionBaseService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 等级记录Service业务层处理
 *
 * @author Lion Li
 * @date 2025-09-02
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SimUserLevelRecordsServiceImpl extends ServiceImpl<SimUserLevelRecordsMapper, SimUserLevelRecords>
    implements ISimUserLevelRecordsService {

    private final ISysUserService sysUserService;

    private final PermissionBaseService permissionBaseService;

    private final SysUserMapper sysUserMapper;

    /**
     * 查询等级记录
     *
     * @param id 主键
     * @return 等级记录
     */
    @Override
    public SimUserLevelRecordsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询等级记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 等级记录分页列表
     */
    @Override
    public TableDataInfo<SimUserLevelRecordsVo> queryPageList(SimUserLevelRecordsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SimUserLevelRecords> lqw = buildQueryWrapper(bo);
        Page<SimUserLevelRecordsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的等级记录列表
     *
     * @param bo 查询条件
     * @return 等级记录列表
     */
    @Override
    public List<SimUserLevelRecordsVo> queryList(SimUserLevelRecordsBo bo) {
        LambdaQueryWrapper<SimUserLevelRecords> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SimUserLevelRecords> buildQueryWrapper(SimUserLevelRecordsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SimUserLevelRecords> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SimUserLevelRecords::getId);
        lqw.eq(bo.getUserId() != null, SimUserLevelRecords::getUserId, bo.getUserId());
        lqw.eq(bo.getSourceLevel() != null, SimUserLevelRecords::getSourceLevel, bo.getSourceLevel());
        lqw.eq(bo.getTargetLevel() != null, SimUserLevelRecords::getTargetLevel, bo.getTargetLevel());
        return lqw;
    }

    /**
     * 新增等级记录
     *
     * @param bo 等级记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SimUserLevelRecordsBo bo) {
        SimUserLevelRecords add = MapstructUtils.convert(bo, SimUserLevelRecords.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改等级记录
     *
     * @param bo 等级记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SimUserLevelRecordsBo bo) {
        SimUserLevelRecords update = MapstructUtils.convert(bo, SimUserLevelRecords.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SimUserLevelRecords entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除等级记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Boolean updateUserLevel(UserLevelBo bo) {
        Long userId = bo.getUserId();
        //ADMIN不参与升级
        if (!ObjectUtil.equal(userId, MachineConstant.ADMIN)) {
            SysUserVo sysUserVo = sysUserService.selectUserById(userId);
            SimUserLevelRecordsBo build = SimUserLevelRecordsBo.builder()
                .userId(userId)
                .sourceLevel(sysUserVo.getLevel())
                .targetLevel(bo.getLevelNum())
                .remark(bo.getRemark())
                .build();
            insertByBo(build);
            sysUserService.updateUserLevel(bo.getUserId(), bo.getLevelNum());
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean manualModificationUserLevel(ManualModificationUserLevelBo bo) {
        Long userId = LoginHelper.getUserId();
        SysUser currentUser = sysUserMapper.selectById(bo.getUserId());

        SysUser sysUser = sysUserMapper.selectById(bo.getUserId());
        BusinessException.isTrue(!ObjectUtil.equal(sysUser.getPId(), userId), "必须由直属代理修改等级！");
        //升级
        UserLevelBo build = UserLevelBo.builder()
            .userId(sysUser.getUserId())
            .levelNum(bo.getLevelNumber())
            .remark(currentUser.getUserName() + "手动调整").build();
        updateUserLevel(build);
        List<Long> user = permissionBaseService.findUser(sysUser, QueryTypeEnum.TEAM.getCode());
        user.forEach(t -> {
            SysUser downUser = sysUserMapper.selectById(t);
            if (downUser.getLevel() > bo.getLevelNumber()) {
                UserLevelBo downUserLevel = UserLevelBo.builder()
                    .userId(sysUser.getUserId())
                    .levelNum(bo.getLevelNumber())
                    .remark(currentUser.getUserName() + "手动调整").build();
                updateUserLevel(downUserLevel);
            }
        });
        return Boolean.TRUE;
    }
}
